<template>
  <div style="padding: 20px">
    <el-breadcrumb separator="/" style="margin-bottom: 20px">
      <el-breadcrumb-item >当前位置：</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a >用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item><a >管理员管理</a></el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-bottom: 10px">
      <el-input v-model="queryParams.title" placeholder="请输入标题" size="small" style="width:200px" clearable></el-input>
      <el-button type="primary" icon="el-icon-search" size="small" @click="getNotice"  >查询</el-button>
      <el-button type="success" icon="el-icon-plus" size="small" @click="open1" v-permission="'notice:addorupdate'">新增</el-button>
    </el-card>
    <el-card style="min-height: 600px">
      <el-table
        :data="tableData"
        border
        style="width: 100%"  highlight-current-row :header-cell-style="headerCellStyle">
        <el-table-column
          prop="id"
          label="编号">
        </el-table-column>
        <el-table-column
          prop="username"
          label="发布用户">
        </el-table-column>
        <el-table-column
          prop="title"
          label="标题">
        </el-table-column>
        <el-table-column
          prop="noticeType"
          label="公告类型">
        </el-table-column>
        <el-table-column
          prop="content"
          label="公告内容" >
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="look(scope.row)">查看</el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="发布时间">
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-circle-plus"  @click="edit(scope.row)">编辑</el-button>
            <el-button type="warning" slot="reference"   size="mini" style="margin-left: 0px" icon="el-icon-delete-solid" @click="delete1(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--        分页-->
      <div class="pagination-container" style="text-align: center">
        <el-pagination
          class="pagiantion"
          v-show="total>0"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[3, 5, 10, 15]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    <!--    删除-->
    <el-dialog :visible.sync="ifdelete" title="删除" width="500px">
      <div style="text-align: center;font-size: 20px">确定删除该数据?</div>
      <div style="text-align: center;margin-top: 20px">

        <el-button type="danger" @click="sure">确定</el-button>
        <el-button type="primary" @click="ifdelete=false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="open" title="新增公告" style="">
      <el-row>
        <el-col :span="2"><div >公告标题:</div></el-col>
        <el-col :span="22">
          <el-input v-model="input"></el-input>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-col :span="2"><div >公告类型:</div></el-col>
        <el-col :span="22">
          <el-input v-model="noticeType"></el-input>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-col :span="2"><div >发布时间:</div></el-col>
        <el-col :span="22">
          <el-date-picker
            v-model="createTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="2"><div style="margin-top: 20px">公告内容:</div></el-col>
        <el-col :span="22"><!--      <div class="ql-editor" v-html="content"></div>-->
<!--          <el-upload-->
<!--            class="avatar-uploader"-->
<!--            action="http://' + process.env.VUE_APP_API_URL + ':8080/uploadfull/"-->
<!--            name="file"-->
<!--            :show-file-list="false"-->
<!--            :on-success="uploadSuccess"-->
<!--            :on-error="uploadError"-->
<!--            :before-upload="beforeUpload"-->
<!--            id="quill-upload">-->
<!--          </el-upload>-->
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :headers="{ 'token':token}"
            name="file"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :before-upload="beforeUpload"
            id="quill-upload">
          </el-upload>
          <el-row v-loading="quillUpdateImg" style="height:380px;">
            <quill-editor
              v-model="content"
              ref="myQuillEditor"
              :options="editorOption"
              @change="onEditorChange($event)"
              @ready="onEditorReady($event)"
            >
            </quill-editor>

          </el-row>
        </el-col>

      </el-row>
      <div style="text-align: right">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="open=false">取消</el-button>
      </div>

    </el-dialog>
    <!--  查看公告-->
    <el-dialog :visible.sync="open2" title="查看公告" style="">
      <div style="text-align: center;font-size: 30px">{{notice.title}}</div>
      <div style="text-align: center;">{{notice.createTime}}</div>
      <div v-html="notice.content" class="ql-editor"></div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment';
import request from "../utils/request";
import {dev as globalConfig} from "../../config";
export default {
  data(){
    //富文本编辑器工具栏
    const toolbarOptions = [
      ['bold', 'italic', 'underline', 'strike'],  // toggled buttons
      //['blockquote', 'code-block'],                      //引用，代码块
      [{'header': 1}, {'header': 2}],    // custom button values
      [{'list': 'ordered'}, {'list': 'bullet'}],
      [{'indent': '-1'}, {'indent': '+1'}],   // outdent/indent
      [{'direction': 'rtl'}],       // text direction
      [{'size': ['small', false, 'large', 'huge']}], // custom dropdown
      [{'header': [1, 2, 3, 4, 5, 6, false]}],
      [{'color': []}, {'background': []}],   // dropdown with defaults from theme
      [{'font': []}],
      [{'align': []}],
      [ "code"],
      [ 'image'],
      ['clean']
    ]
    return{
      title:'',
      notice:{},
      false:[],
      content: ``,
      token:localStorage.getItem("token"),
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      editorOption: {
        placeholder: '请输入文章内容',
        theme: 'snow',
        modules: {
          //         // 新增下面代码
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('#quill-upload input').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          }
        }
      },
      ifshow:false,
      total:0,
      tableData:[{}],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title:undefined
      },
      input:'',
      noticeType:undefined,
      createTime:undefined,
      open2:false,
      id:undefined,
      open:false,
      deleteid:'',
      ifdelete:false,
    }
  },
  computed: {
    uploadAction() {
      return 'http://' + globalConfig.host + ':8090/uploadquill/';
    }
  },
  created() {
    this.getNotice()
  },
  methods:{
    sure(){
      let url='/deleteid'
      let param={
        id:this.deleteid
      }
      request.post(url,param).then(resp=>{
        if (resp.code===200){
          this.getNotice()
          this.ifdelete=false
          this.$message.success(resp.errorMessage)
        }
      })
    },
    //查看公告
    look(i){
      this.notice.title=i.title
      this.notice.content=i.content
      this.notice.noticeType=i.noticeType
      this.notice.createTime=i.createTime
      this.notice.createTime=i.createTime
      this.open2=true
    },
    //删除
    delete1(i){
      this.ifdelete=true
      this.deleteid=i.id
    },
    //编辑
    edit(i){
      this.content=i.content
      this.input=i.title
      this.id=i.id
      this.noticeType=i.noticeType
      this.createTime=i.createTime
      this.open=true
    },
    open1(){
      this.id=undefined
      this.content=undefined
      this.input=undefined
      this.noticeType=undefined
      this.createTime=undefined
      this.open=true
    },

    //清楚数据
    clear1(){
      this. adddata={}
    },
    //添加
    submit(){
      let url='/addNotice'
      let param={
        id:this.id,
        title:this.input,
        content:this.content,
        noticeType:this.noticeType,
        createTime:moment(this.createTime).format('YYYY-MM-DD HH:mm:ss')
      }
      request.post(url,param,{
        headers: {
          'content-type': 'application/json',
          "token": localStorage.getItem("token")  //token换成从缓存获取
        }
      }).then(resp=>{
        if (resp.code===200){
          this.getNotice()
          this.open=false
          this.content=undefined
          this.input=undefined
          this.createTime=undefined
          this.message(resp.errorMessage,'success')
        }else {
          this.message(resp.errorMessage,'error')
        }
      }).catch((error) => this.message('没有权限','error'));
    },
    //分页
    handleSizeChange(val){
      this.queryParams.pageSize = val;
      this.queryParams.pageNum = 1;
      this.getNotice()
    },
    handleCurrentChange(val){
      this.queryParams.pageNum = val;
      this.getNotice()
    },
    getNotice(){
      let url='/getNotice'
      request.post(url,this.queryParams).then(resp=>{
        if (resp.code===200){
          this.tableData=resp.list
          this.total=resp.total
        }
      })
    },
    // 上传图片前
    beforeUpload(res, file) {
      this.quillUpdateImg = true
    },
    // 上传图片成功
    uploadSuccess(res, file) {
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill
      // 如果上传成功
      quill.insertEmbed(quill.getSelection().index, 'image', res.data)
      this.quillUpdateImg = false

      if (res.code === 200 ) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片 res.info为服务器返回的图片地址

        quill.insertEmbed(length, 'image', file)
        // 调整光标到最后
        quill.setSelection(length + 1)
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      this.quillUpdateImg = false
    },
    // 上传图片失败
    uploadError(res, file) {
      // loading动画消失
      this.quillUpdateImg = false
      this.$message.error('图片插入失败')
    },
    headerCellStyle(column) {
      return { backgroundColor: '#C7E3FF',color: '#1f2f3d' }
    },
  }
}
</script>

<style scoped>
>>> .ql-container {
  height: 300px;
}
>>> .el-dialog__header {
  background-color: #66b1ff;
}
</style>
